package com.eportal.thread;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Random;

import mpi.client.data.OrderData;
import mpi.client.exception.PayException;
import mpi.client.trans.TopPayLink;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import cfca.util.Base64;

import com.eportal.ORM.NetPayJnls;
import com.eportal.ORM.NetPayJnlsId;
import com.eportal.ORM.NetPayJnlsPl;
import com.eportal.chinapay.SignData;
import com.eportal.core.Util;
import com.eportal.service.AdminService;
import com.eportal.struts.action.NetPayAction;

public class Dkpay extends Thread {
	
	AdminService service;
	AdminService serviceOracle;
	
	
	
	public AdminService getService() {
		return service;
	}
	public void setService(AdminService service) {
		this.service = service;
	}
	public AdminService getServiceOracle() {
		return serviceOracle;
	}
	public void setServiceOracle(AdminService serviceOracle) {
		this.serviceOracle = serviceOracle;
	}
	List <NetPayJnlsPl> list;
	public Dkpay(List <NetPayJnlsPl> list){
		this.list = list;
	}
	public void run(){
		System.out.println("处理数据。。");
		for(int i = 0;i<list.size();i++){
			String message  ="";
			NetPayJnlsPl net = list.get(i);
			Random random = new Random();
			int id = random.nextInt(99999999);
			// 判定代扣渠道
			String str = checkBin(net.getPan(), "1");
			char isDk = '0';
			char qdao = '0';
			String bank = "";
			try {
				isDk = str.charAt(0);
				qdao = str.charAt(1);
				bank = str.substring(2);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				message = "不支持该银行卡，如有疑问，联系客服。";
				OrderData tstOrderData = new OrderData();
				// 以下字段是无密代扣交易必输字段
				tstOrderData.setTranCode("1040");
				// 商户ＩＤ（每个商户对应唯一的ID）
				tstOrderData.setMerchantID(NetPayAction.shopno);
				// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
				tstOrderData.setMerOrderNum("4038" + "1597"
						+ Util.addZero("" + id, 8));
				// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
				tstOrderData.setTranDateTime(Util
						.getCurrentDate("yyyyMMddHHmmss"));
				tstOrderData.setPan(net.getPan());
				// 币种（人民币：156）
				tstOrderData.setCurType("156");
				// 交易金额(单位：分)
				tstOrderData.setTranAmt(net.getTranamt());
				tstOrderData.setChInfo("", "", "", "", "", "");
				// 以下字段是无密代扣交易可输字段
				tstOrderData.setCustName(net.getCustname());
				// tstOrderData.setMsgExt(payRemark);
				NetPayJnls nn = new NetPayJnls();
				nn.setCustname(tstOrderData.getCustName());
				nn.setTrancode("1040");
				nn.setMerchantid(tstOrderData.getMerchantID());
				nn.setOrgcode(net.getOrgcode());
				nn.setPan(tstOrderData.getPan());
				nn.setRespcode("FF");
				nn.setRemark(net.getRemark());
				nn.setRespdesc(message);
				nn.setProdinfo(net.getProdinfo());
				nn.setMsgext(net.getMsgext());
				
				nn.setTranamt(tstOrderData.getTranAmt());
				nn.setTrandatetime(new Timestamp(new Date().getTime()));

				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
				nid.setMerordernum(tstOrderData.getMerOrderNum());
				nn.setId(nid);
				this.serviceOracle.save(nn);
				continue;
			}
			if (isDk == '1') {// 支持代扣
				if (qdao == '0') {// 互联网渠道
					String MPIURL = Util.ROOTPATH + "/netPay/MPI.properties";
					System.out.println(MPIURL);
					try {
						System.setProperty("javax.net.ssl.trustStore",
								Util.ROOTPATH + "/netPay/jssecacerts");
						TopPayLink.setMPIpropertiesFilePath(MPIURL);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					OrderData tstOrderData = new OrderData();
					// 以下字段是无密代扣交易必输字段
					tstOrderData.setTranCode("1040");
					// 商户ＩＤ（每个商户对应唯一的ID）
					tstOrderData.setMerchantID(NetPayAction.shopno);
					// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
					tstOrderData.setMerOrderNum("4038" + "1597"
							+ Util.addZero("" + id, 8));
					// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
					tstOrderData.setTranDateTime(Util
							.getCurrentDate("yyyyMMddHHmmss"));
					tstOrderData.setPan(net.getPan());
					// 币种（人民币：156）
					tstOrderData.setCurType("156");
					// 交易金额(单位：分)
					tstOrderData.setTranAmt(net.getTranamt());
					tstOrderData.setChInfo("", "", "", "", "", "");
					// 以下字段是无密代扣交易可输字段
					tstOrderData.setCustName(net.getCustname());
					// tstOrderData.setMsgExt(payRemark);
					NetPayJnls nn = new NetPayJnls();
					nn.setCustname(tstOrderData.getCustName());
					nn.setTrancode("1040");
					nn.setMerchantid(tstOrderData.getMerchantID());
					nn.setOrgcode(net.getOrgcode());
					nn.setPan(tstOrderData.getPan());
					nn.setRespcode("SS");

					nn.setRespdesc("发送超时");
					nn.setProdinfo(net.getProdinfo());
					nn.setMsgext(net.getMsgext());
					nn.setRemark(net.getRemark());
					nn.setTranamt(tstOrderData.getTranAmt());
					nn.setTrandatetime(new Timestamp(new Date().getTime()));

					NetPayJnlsId nid = new NetPayJnlsId();
					nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
					nid.setMerordernum(tstOrderData.getMerOrderNum());
					nn.setId(nid);
					this.serviceOracle.save(nn);
					try {
						// 调用交易接口发送到中国银联互联网收单服务平台并同步接收返回结果
						// 商户可根据返回结果进行相关后续处理
						tstOrderData = TopPayLink.CollPayTrans(tstOrderData);

						if (tstOrderData == null) {
							System.out.println("TopPayLink.CollPayTrans error");
						} else {
							// 打印返回交易结果码,返回6个0(000000)表示交易成功
							// 其他的交易码可参考MPI商户插件文档（附录一）.
							System.out.println("Txn RespCode is : "
									+ tstOrderData.getRespCode());
						}
					} catch (PayException ex) {
						System.out
								.println("TopPayLink.CollPayTrans error: RespCode =["
										+ ex.getErrCd() + "]");
						tstOrderData.setRespCode(ex.getErrCd());
						ex.printStackTrace();
						message = "发送失败，请稍候在试！";
						nn.setRespcode("FF");
						nn.setRespdesc(message);
						this.serviceOracle.saveOrUpdate(nn);
						continue;
					} catch (Exception ex) {
						ex.printStackTrace();
						System.out.println("TopPayLink.CollPayTrans error 2");
						message = "发送失败，请稍候在试！";
						nn.setRespcode("FF");
						nn.setRespdesc(message);
						this.serviceOracle.saveOrUpdate(nn);
						continue;
					}
					Connection c = serviceOracle.getConnection();
					try {
						PreparedStatement ps = c
								.prepareStatement("update net_pay_jnls set RESPCODE = '"
										+ tstOrderData.getRespCode()
										+ "',CUPSSYSTIME  = '"
										+ tstOrderData.getCupsSysTime()
										+ "',CUPSTRACENUM = '"
										+ tstOrderData.getCupsTraceNum()
										+ "',SETTLEDATE = '"
										+ tstOrderData.getSettleDate()
										+ "',RESPDESC = '"
										+ tstOrderData.getRespDesc()
										+ "' where MERORDERNUM = '"
										+ tstOrderData.getMerOrderNum()
										+ "' and PEPDATE = '"
										+ Util.getCurrentDate("yyyyMMdd") + "'");
						ps.executeUpdate();
						c.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {// chinapay渠道
					HttpClient httpClient = new HttpClient();
					httpClient.getParams().setParameter(
							HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
					String url = "http://apps.chinapay.com/witsingletran/WitSinTranServlet";
					PostMethod postMethod = new PostMethod(url);
					String merId = "808080450004842";
					String transDate = Util.getCurrentDate("yyyyMMdd");
					String orderNo = "50004842" + Util.addZero("" + id, 8);
					String transType = "0003";
					String openBankId = Util.checkBank(bank.trim());
					String cardType = "0";
					String cardNo = net.getPan();
					String usrName1 = net.getCustname();
					String tianUn = toUnicode(usrName1);
					String tmpUsrName = tianUn;
					String certType = "01";
					String certId = "310000000000000000";
					String curyId = "156";
					String transAmt = net.getTranamt();
					String purpose = "";
					String priv1 = "00";
					String tmpPriv1 = toUnicode(priv1);
					String version = "20100831";
					String gateId = "7008";

					StringBuffer retStr = new StringBuffer();
					retStr.append(merId).append(transDate).append(orderNo).append(
							transType).append(openBankId).append(cardType).append(
							cardNo).append(tmpUsrName).append(certType).append(
							certId).append(curyId).append(transAmt)
							.append(tmpPriv1).append(version).append(gateId);

					SignData signData = new SignData();
					if (Util.ROOTPATH.equals("")) {
						continue;
					}
					signData.setPath(Util.ROOTPATH + "/chinapay/");
					String data0 = new String(Base64.encode(retStr.toString()
							.getBytes()));
					String chkValue = signData.signForCP(merId, data0);
					NameValuePair[] data = { new NameValuePair("merId", merId),
							new NameValuePair("transDate", transDate),
							new NameValuePair("orderNo", orderNo),
							new NameValuePair("transType", transType),
							new NameValuePair("openBankId", openBankId),
							new NameValuePair("cardType", cardType),
							new NameValuePair("cardNo", cardNo),
							new NameValuePair("usrName", tmpUsrName),
							new NameValuePair("certType", certType),
							new NameValuePair("certId", certId),
							new NameValuePair("curyId", curyId),
							new NameValuePair("transAmt", transAmt),
							new NameValuePair("purpose", purpose),
							new NameValuePair("priv1", tmpPriv1),
							new NameValuePair("version", version),
							new NameValuePair("gateId", gateId),
							new NameValuePair("chkValue", chkValue) };

					postMethod.setRequestBody(data);
					NetPayJnls nn = new NetPayJnls();
					nn.setCustname(net.getCustname());
					nn.setTrancode("0003");
					nn.setMerchantid(merId);
					nn.setMsgext(net.getMsgext());
					nn.setOrgcode(net.getOrgcode());
					nn.setPan(net.getPan());
					nn.setRespcode("SS");

					nn.setRespdesc("发送超时");
					nn.setProdinfo(net.getProdinfo());
					nn.setMsgext(net.getMsgext());
					nn.setTranamt(net.getTranamt());
					nn.setTrandatetime(new Timestamp(new Date().getTime()));
					nn.setRemark(net.getRemark());
					NetPayJnlsId nid = new NetPayJnlsId();
					nid.setPepdate(transDate);
					nid.setMerordernum(orderNo);
					nn.setId(nid);
					this.serviceOracle.save(nn);
					int statusCode = 0;
					try {
						statusCode = httpClient.executeMethod(postMethod);
					} catch (HttpException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (statusCode != HttpStatus.SC_OK) {
						System.out.println("Method failed:"
								+ postMethod.getStatusLine());
					}
					String tian = "";
					String responseCode = "";
					try {
						tian = postMethod.getResponseBodyAsString();
						System.out.println("html:" + tian);
						responseCode = tian.substring(13, 15);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String msg = "";

					if (!responseCode.equals("")) {
						if (!responseCode.equals("45")) {
							msg = (String) Util.CHINALIST.get(responseCode);
						} else {
							String tiakong = tian;
							int dex = tian.lastIndexOf("=");

							String tmp = "";
							String tmp2 = "";
							if (tiakong.indexOf("message") != -1) {
								msg = tiakong
										.substring(tiakong.indexOf("message") + 8);
								tmp = tiakong.substring(0, tiakong
										.indexOf("message") + 8);
								tmp2 = msg.substring(msg.indexOf("&", 1));
								msg = msg.substring(0, msg.indexOf("&", 1));
							}
							msg = tozhCN(msg);
						}
						if (msg == null || msg.equals(""))
							msg = "交易失败";
						Connection c = serviceOracle.getConnection();
						try {
							PreparedStatement ps = c
									.prepareStatement("update net_pay_jnls set RESPCODE = '"
											+ responseCode
											+ "',RESPDESC = '"
											+ msg
											+ "' where MERORDERNUM = '"
											+ orderNo
											+ "' and PEPDATE = '"
											+ Util.getCurrentDate("yyyyMMdd") + "'");
							ps.executeUpdate();
							c.close();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				service.delete(net);
			} else {
				OrderData tstOrderData = new OrderData();
				// 以下字段是无密代扣交易必输字段
				tstOrderData.setTranCode("1040");
				// 商户ＩＤ（每个商户对应唯一的ID）
				tstOrderData.setMerchantID(NetPayAction.shopno);
				// 订单号（生成规则：从商户ID第四位开始的四位[4401]+取商户ID倒数四位[0027]+8位随机序列号）
				tstOrderData.setMerOrderNum("4038" + "1597"
						+ Util.addZero("" + id, 8));
				// 交易时间(注意位数:14位，交易时间和系统当前时间相差不超过2个小时)：20101125112433
				tstOrderData.setTranDateTime(Util
						.getCurrentDate("yyyyMMddHHmmss"));
				tstOrderData.setPan(net.getPan());
				// 币种（人民币：156）
				tstOrderData.setCurType("156");
				// 交易金额(单位：分)
				tstOrderData.setTranAmt(net.getTranamt());
				tstOrderData.setChInfo("", "", "", "", "", "");
				// 以下字段是无密代扣交易可输字段
				tstOrderData.setCustName(net.getCustname());
				// tstOrderData.setMsgExt(payRemark);
				NetPayJnls nn = new NetPayJnls();
				nn.setCustname(tstOrderData.getCustName());
				nn.setTrancode("1040");
				nn.setMerchantid(tstOrderData.getMerchantID());
				nn.setOrgcode(net.getOrgcode());
				nn.setPan(tstOrderData.getPan());
				nn.setRespcode("FF");
				nn.setRemark(net.getRemark());
				nn.setRespdesc(message);
				nn.setProdinfo(net.getProdinfo());
				nn.setMsgext(net.getMsgext());
				
				nn.setTranamt(tstOrderData.getTranAmt());
				nn.setTrandatetime(new Timestamp(new Date().getTime()));

				NetPayJnlsId nid = new NetPayJnlsId();
				nid.setPepdate(tstOrderData.getTranDateTime().substring(0, 8));
				nid.setMerordernum(tstOrderData.getMerOrderNum());
				nn.setId(nid);
				this.serviceOracle.save(nn);
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	
	// 校验卡BIN
	public String checkBin(String card, String flag) {
		String sql = "select t.net_iss_flag,t.net_iss_card,p.lc_card,NET_ISS_RZ,NET_ISS_DK,NET_ISS_NAME from net_pay_iss t, pep_card_limit p where t.net_iss_id = trim(p.lc_iss_id) and length(trim('"
				+ card
				+ "')) = p.lc_cdnopos and substr(trim('"
				+ card
				+ "'),0,length(trim(p.lc_head)))= trim(p.lc_head)";
		Connection c = serviceOracle.getConnection();
		String tmp = "";
		try {
			PreparedStatement ps = c.prepareStatement(sql);
			ResultSet rset = ps.executeQuery();
			rset.next();
			String net_iss_flag = rset.getString(1);
			String net_iss_card = rset.getString(2);
			String lc_card = rset.getString(3);
			String net_rz = rset.getString(4);
			String net_dk = rset.getString(5);
			String net_name = rset.getString(6);
			if (flag.equals("0")) {// 消费
				if (net_iss_flag.equals("0") || net_iss_flag.equals("2")) {
					if (lc_card.equals("D")) {
						if (net_iss_card.equals("0")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk;
						}
					} else {
						if (net_iss_card.equals("1")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk;
						}
					}
				}
			} else if (flag.equals("1")) {// 代扣
				if (net_iss_flag.equals("1") || net_iss_flag.equals("2")) {
					if (lc_card.equals("D")) {
						if (net_iss_card.equals("0")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk + net_name;
						}
					} else {
						if (net_iss_card.equals("1")
								|| net_iss_card.equals("2")) {
							tmp = 1 + net_dk + net_name;
						}
					}
				}
			} else if (flag.equals("2")) {// 认证
				if (net_rz != null && net_rz.equals("1")) {
					tmp = 1 + net_dk;
				} else {
					tmp = 0 + net_dk;
				}
			}
			c.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tmp = "00";
		}

		return tmp;
	}

	public static String tozhCN(String unicode) {
		StringBuffer gbk = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			int data = Integer.parseInt(hex[i], 16);
			gbk.append((char) data);
		}
		return gbk.toString();
	}

	public static String toUnicode(String zhStr) {
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < zhStr.length(); i++) {
			char c = zhStr.charAt(i);
			unicode.append("\\u" + Integer.toHexString(c));
		}
		System.out.println(unicode.toString());
		return unicode.toString();
	}
}
